﻿using System.Text.Json;

namespace License
{
    public class LicenseHelper
    {
        /// <summary>
        /// 客户端验证License，存储
        /// </summary>
        /// <param name="lic">服务端授权给客户的License密文</param>
        /// <returns></returns>
        public static LicenseResult Verify(string lic)
        {
            var aeskey = "wklic@;&tu@"; //密钥
            var aesIV_128 = "wk666&/@"; //8位密钥
            var result = new LicenseResult();
            try
            {
                if (string.IsNullOrEmpty(lic))
                {
                    throw new Exception("license为空");
                }
                var strLic = EncodeHelper.AESDecrypt(lic, aeskey, aesIV_128);
                if (string.IsNullOrEmpty(strLic))
                {
                    throw new Exception("license无效");
                }
                var licByte = Convert.FromBase64String(strLic);
                var lm = JsonSerializer.Deserialize<LicenseModel>(licByte);
                if (lm.CustomRole == RoleType.Trial && lm.ExpireTime < DateTime.Now)
                {
                    throw new Exception("license已过期");
                }

                result.ExpireTime = lm.CustomRole == RoleType.Trial ? lm.ExpireTime.ToShortDateString() : "无";
                result.Version = lm.CustomRole == RoleType.Trial ? "授时版" : "永久版";
                result.Message = lm.CustomRole == RoleType.Trial ? $"{result.Version},过期时间：{result.ExpireTime}" : result.Version;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                result.SetMessage(ex.Message);
            }
            return result;
        }
    }
    public class LicenseResult
    {
        public bool Result { get; set; } = true;
        public string Message { get; set; }
        public string Version { get; set; }
        public string ExpireTime { get; set; }

        public void SetMessage(string message)
        {
            Result = false;
            Message = message;
        }
    }

    public class LicenseModel
    {
        //过期时间expire
        public DateTime ExpireTime { get; set; }
        //权限类型（如可分为 0： 15天试用版  1：1年版  2：终身版）
        public RoleType CustomRole { get; set; }
    }

    public enum RoleType
    {
        /// <summary>
        /// 试用版
        /// </summary>
        Trial = 0,
        /// <summary>
        /// 终身版
        /// </summary>
        Free = 2
    }
}